import std.stdio;
import std.array;
import std.process;
import std.string;
import std.c.linux.linux;
import std.conv;

/+

dmd -O -release -inline -m64 proctest.d

+/

// single processor core 2duo desktop no stdlib - raw C min program - 2500 execv/sec
// single processor core 2duo desktop no stdlib - D program - 1000 execv/sec

/+

12core 24cpu-hyperthread X5680 3.3GHz D language - 28_000 execv/sec
real	0m14.146s
user	1m33.121s
sys	3m19.338s
[root@dc331 /home/denny]# time ./proctest 5000 fork 80


+/

int main(string[] args){
//  int count = atoi(args[1]);
  auto count = parse!(uint)(args[1]);

  if( args.length>2 && args[2]=="fork" ){
    int[] children;
    foreach( i ; 0..parse!(uint)(args[3])){
      int pid = fork();
      if( pid==0 ){
        execve("./proctest",["proctest", text(count)], []);
      }else{
	children ~= pid;
      }
    }
    writeln("children ",children);
    foreach( pid; children ){
      int status;
      waitpid(pid, &status, 0);
      writeln(pid," status ",status);
    }
    return 0;
  }

//	writeln("hello-start",count);
  if( count>0 ){
     execve("./proctest",["proctest", text(count-1), "mmmmmmmmmmm---mmmmmmmmmmmm"], []);
  }
//writeln(shell("df -h"));
//writeln(shell("df -h"));

//foreach( i; 1..100 ){
//  writeln(chomp(shell("uname -a"))); // linux64 home notebook - 2ms
//}

//writeln("fork value",fork());
//scope(exit) writef("3-exit-scope");
/*
try{
	execv("/bin/bash",["bash", "-c", "touch a1.touch"]);
}
    catch(Exception e)
    {
	writefln("catch %s", e.msg);
    }finally{
	writeln("aaa");
    }
*/
//if( fork()==0 ){
//  execv("/bin/bash",["bash", "-c", "touch a2.touch"]);
//}
//	execv("/usr/bin/touch",["touch","a.touch"]);
//	execv("/usr/bin/touch",["touch","b.touch"]);

//	execv("/usr/bin/java",["java","-version"]);
//	execv("/usr/bin/java",["java","-version"]);




	writeln("hello-end",count);
	return 15;
}
